import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  
  return {
    plugins: [vue()],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    server: {
      port: 3000,
      open: true,
      // 开发环境代理配置
      proxy: {
        '/api': {
          target: 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
          // 当后端服务不可用时，MockJS会拦截请求
          configure: (proxy, options) => {
            proxy.on('error', (err, req, res) => {
              console.log('代理请求失败，MockJS将处理请求:', err.message)
            })
          }
        }
      }
    },
    // 构建配置
    build: {
      // 生产环境不包含MockJS
      rollupOptions: {
        external: mode === 'production' ? ['mockjs'] : []
      }
    },
    // 环境变量配置
    define: {
      // 在开发环境启用MockJS
      __MOCK_ENABLED__: JSON.stringify(mode === 'development'),
      // 注入环境变量到客户端
      __APP_ENV__: JSON.stringify(mode)
    }
  }
}) 